﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace TripleGameWCFService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TripleGameService" in code, svc and config file together.
    public class TripleGameService : ITripleGameService
    {
        public string ReserveNewUserId(string name)
        {
            TripleGameBaseEntities tripleGameBaseEntities = new TripleGameBaseEntities();
            Users newUser = new Users()
            {
                 Username = name
            };
            tripleGameBaseEntities.Users.AddObject(newUser);
            tripleGameBaseEntities.SaveChanges();
            return newUser.UserID.ToString();
        }


        public string MakeMove(string x1, string y1, string x2, string y2)
        {
            return x1 + " " + y1 + " " + x2 + " " + y2;
        }

        private static string GetTable(int creatorId)
        {
            TripleGameBaseEntities tripleGameBaseEntities = new TripleGameBaseEntities();
            string table = tripleGameBaseEntities.Rooms.FirstOrDefault(room => room.CreatorID == creatorId).GameTable;
            return table;
        }

        private static int[] ParseTable(string table)
        {
            const int ROWS = 5;
            const int COLS = 10;
            int[] result = new int[ROWS * COLS];
            for (int i = 0; i < ROWS; i++)
            {
                for (int j = 0; j < COLS; j++)
                {
                    char current = table[i*COLS + j];
                    result[i*COLS + j] = int.Parse(current+"");
                }
            }
            return result;
        }


        public int[] GetMatrix(string gameId)
        {
            int creatorId = int.Parse(gameId);
            string unparsedBoard = GetTable(creatorId);
            int[] table = ParseTable(unparsedBoard);
            return table;
        }
    }
}
